package com.zqm.experiment3.Service.impl;


import com.zqm.experiment3.Pojo.COVID19Data;
import com.zqm.experiment3.Pojo.COVID19DataList;
import com.zqm.experiment3.Service.COVID19MsgService;
import com.zqm.experiment3.utils.HTTPUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class COVID19MsgServiceImpl implements COVID19MsgService {

    @Value("${covid-19-csv-url}")
    private String csvUrl;

    public static List<COVID19Data> CONFIRMED = new ArrayList<>();

    @Override
    @Scheduled(cron = "${zqm.Schedules.updateVirusDataCron}")
    @PostConstruct
    public void getDataFromGit() throws IOException {
        //发送http请求获取csv文件流
        Resource resource = HTTPUtil.sendHttp(csvUrl);
        //解析csv文件
        HTTPUtil.CSVParserAndRecord(resource,CONFIRMED);
    }

    @Override
    public COVID19DataList getCovid19Msg(String region) {
        COVID19DataList cOVID19DataList =new COVID19DataList();
        if(region != null) {
            List<COVID19Data> collect = CONFIRMED.stream()
                    .filter(cOVID19Data -> cOVID19Data.getRegion().compareTo(region) == 0)
                    .collect(Collectors.toList());
            if(collect.size() != 0) {
                cOVID19DataList.setCovid19DataList(collect);
            }

        } else {
            cOVID19DataList.setCovid19DataList(CONFIRMED);
        }
        return cOVID19DataList;
    }
}